package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    DishService dishService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    /*###### 接口2：添加菜品【复杂】
    备注：涉及表 Dish【菜品表】、Dish_flavor【菜品口味表】
    请求url地址：/dish
    请求方式：POST
    请求参数：JSON格式数据 ---> 用什么对象封装  Dish  DishFlavor 都不是！用新的实体类 DishDto;*/




    //添加菜品的方法 如果添加了菜品 将缓存中的菜品清空
    @PostMapping
    public R dishAdd(@RequestBody DishDto dishDto) {
        Dish dish = new Dish();
        //DishFlavor dishFlavor = new DishFlavor();
        /*"name": "辣白菜",
        "price": 1100,
        "code": "",
        "image": "2498cbdc-cdea-4e3a-886f-79cc01c7d9f6.jpg",
        "description": "好，非好吃！",
        "status": 1,
        "categoryId": "1397844303408574465",*/
        dish.setName(dishDto.getName());
        dish.setPrice(dishDto.getPrice());
        dish.setCode(dishDto.getCode());
        dish.setImage(dishDto.getImage());
        dish.setDescription(dishDto.getDescription());
        dish.setStatus(dishDto.getStatus());
        dish.setCategoryId(dishDto.getCategoryId());
        dishService.save(dish);
        /*"flavors": [{
		"name": "辣度",
		"value": "[\"不辣\",\"微辣\",\"中辣\",\"重辣\",\"变态辣\"]",
		"showOption": false
	     }]*/
        List<DishFlavor> flavors = dishDto.getFlavors();
        //判断是否选择了口味
        if (flavors != null && flavors.size() > 0) {
            //保存菜品的口味数据 需要注意：DishFlavor中dishId是没有数据的，
            // 所以需要手动设置
            Long dishId = dish.getId();//获取菜品id
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
                dishFlavorService.save(flavor);
            }
        }
        /**
         * 添加菜品成功 清理改菜品分类的缓存信息
         */
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        return R.success("dish");
    }





    /*#### 接口四：分页查询菜品数据
    请求url地址：/dish/page ?page=1&pageSize=10&name=白菜
    请求方式：GET
    请求参数：?page=1&pageSize=10&name=白菜*/
    @GetMapping("/page")
    public R selectPage(int page, int pageSize, String name) {

        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(name != null && name != "", Dish::getName, name);
        wrapper.lambda().orderByDesc(Dish::getUpdateTime);
        Page<Dish> dishPage = new Page<>(page, pageSize);
        dishService.page(dishPage, wrapper);
        //总条数
        Long total = dishPage.getTotal();
      /*  if(1==1){
            throw new RepeatException(String.valueOf(total));
        }*/
        List<Dish> records = dishPage.getRecords();
        //创建一个dishdto集合接收dto对象
        List<DishDto> dtoList = new ArrayList<>();
        for (Dish dish : records) {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(dish, dto);
            Long id = dish.getCategoryId();
            String s = categoryService.getById(id).getName();
            dto.setCategoryName(s);
            dtoList.add(dto);
        }
        Page page1 = new Page();
        page1.setRecords(dtoList);
        page1.setTotal(total);
        return R.success(page1);
    }

    //查询单个 用于数据回显
    @GetMapping("/{id}")
    public R selectById(@PathVariable long id) {
        DishDto dishDto = new DishDto();
        Dish byId1 = dishService.getById(id);
        BeanUtils.copyProperties(byId1, dishDto);
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }


    /**
     * 修改菜品 如果数据发生修改 则将改分类的缓存信息清空
     * @param dishDto
     * @return
     */
    //修改菜品
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);
        Long id = dish.getId();
        dishService.updateById(dish);
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        //获取用户选择的口味集合
        QueryWrapper<DishFlavor> wrapper1 = new QueryWrapper<>();
        wrapper1.lambda().eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(wrapper1);

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (int i = 0; i < flavors.size(); i++) {
            flavors.get(i).setDishId(dishDto.getId());
            dishFlavorService.save(flavors.get(i));
        }
        String key = "dish_"+ dishDto.getCategoryId() +"_"+dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    //删除菜品
    //删除菜品有可能是批量删除 所有当出现删除数据时 则将缓存中的数据清空
    @DeleteMapping
    public R deletes(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        List<Dish> setmeals = dishService.listByIds(Arrays.asList(ids));
        for (Dish dish : setmeals) {
            if(dish.getStatus()==1){
                return R.error("启售中无法删除");
            }
        }
        dishService.removeByIds(list);


        /**
         * 方法一  如果数据发生修改 则清空所有的菜品数据
         */
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);



        return R.success("删除成功");
    }

    //起售 停售 批量停售 批量起售
    @PostMapping("/status/{status}")
    public R status(@PathVariable Integer status, Long[] ids) {
        //获取所有的id
        List<Long> longs = Arrays.asList(ids);
        //获取ids所有的对象
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        //wrapper.lambda().eq(Dish::getStatus,status);
        wrapper.lambda().in(Dish::getId, ids);
        List<Dish> list = dishService.list(wrapper);
           /* if(status==1){
                for (Dish dish : list) {
                    dish.setStatus(1);
                    dishService.updateById(dish);
                }
            }else {
                for (Dish dish : list) {
                    dish.setStatus(0);
                    dishService.updateById(dish);
                }
            }*/
        int s1 = status == 1 ? 1 : 0;
        for (Dish dish : list) {
            dish.setStatus(s1);
            dishService.updateById(dish);
        }
        return R.success("操作成功");
           /* List<Dish> dishList = dishService.listByIds(longs);
            if(status==1){
                for (Dish dish : dishList) {
                    dish.setStatus(1);
                    dishService.updateById(dish);
                }
                return R.success("操作成功");
            }else {
                for (Dish dish : dishList) {
                    dish.setStatus(0);
                    dishService.updateById(dish);
                }
                return R.success("操作成功");
            }*/
    }

    //查询菜品数据 先判断缓存中有没有菜品数据 如果有 则返回缓存中的菜品数据 如果没有 则正常查询 将数据存入缓存中
    //根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")
    public R getList(Long categoryId, Integer status) {
        /**
         * 判断缓存中是否有该菜品数据 如果有则返回缓存信息 如果没有 则查询信息后存入缓存中
         */
        String key = "dish_" + categoryId +"_"+status;

        List<DishDto> o1 = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(o1!=null){
            return R.success(o1);
        }

        if(status==null){
            QueryWrapper<Dish> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(Dish::getCategoryId,categoryId);

            List<Dish> list = dishService.list(wrapper);
            return R.success(list);
        }
        //获取条件构造器
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Dish::getCategoryId, categoryId);
        wrapper.lambda().eq(Dish::getStatus,status);
        //获取id下所有的菜品
        List<Dish> list = dishService.list(wrapper);
        //创建一个dto集合
        List<DishDto> dtoList = new ArrayList<>();
        for (Dish dish : list) {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(dish,dto);
            QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper);
            dto.setFlavors(list1);
            dtoList.add(dto);
        }
        redisTemplate.opsForValue().set(key,dtoList);
        return R.success(dtoList);
    }
        /*@GetMapping("/list")
        public R getList(Long categoryId){
            QueryWrapper<Dish> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(Dish::getCategoryId,categoryId);

            List<Dish> list = dishService.list(wrapper);
            return R.success(list);
        }*/

    //新增套餐接口


}
